package ywpt.web.action.system;

import ywpt.components.acegi.domain.User;
import ywpt.core.exception.BusinessException;
import ywpt.core.web.BaseAction;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import ywpt.web.common.StringUtil;

import ywpt.service.system.UserService;

import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

public class PasswordAction extends BaseAction implements ModelDriven<User>, Preparable {
	private static final long	serialVersionUID	= -5511353482856958122L;
	protected final Log			log					= LogFactory.getLog(PasswordAction.class);
	private Long				id;
	private String				username;
	private String				oldPassword;
	private String				password;
	private String				confirmPassword;
	private User				user;
	private UserService			userService;
	protected static int		DEFAULT_PAGE_SIZE	= 20;
	protected static String		ENC_ALGORITHM		= "MD5";

	public PasswordAction() {
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getOldPassword() {
		return oldPassword;
	}

	public void setOldPassword(String oldPassword) {
		this.oldPassword = oldPassword;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String newPassword) {
		this.password = newPassword;
	}

	public String getConfirmPassword() {
		return confirmPassword;
	}

	public void setConfirmPassword(String confirmPassword) {
		this.confirmPassword = confirmPassword;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public User getModel() {
		return user;
	}

	@Override
	@SuppressWarnings("unchecked")
	public String execute(){
		return INPUT;
	}

	public String updatePassword() throws Exception {
		this.oldPassword = StringUtil.encodePassword(this.oldPassword, ENC_ALGORITHM);
		if (!userService.checkPassword(username, oldPassword)) {
			this.addActionError("输入旧密码错误,请重新输入!");
			return INPUT;
		}
		this.password = StringUtil.encodePassword(this.password, ENC_ALGORITHM);
		this.confirmPassword = StringUtil.encodePassword(this.password, ENC_ALGORITHM);
		try {
			userService.updatePassword(username, password);
			this.addActionMessage("成功更新密码!");
		} catch (BusinessException e) {
			this.addActionError("更新错误密码!");
			return INPUT;
		}
		return INPUT;
	}

	public void prepare() throws Exception {
		this.username = this.getCurrentUserName();
	}
}